package com.project8.book;

import java.io.Serializable;
import java.util.ArrayList;

public class TableOfBookmarks implements Serializable 
{		
	private static final long serialVersionUID = 1720951630407323321L;
	
		ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>();
		
		public TableOfBookmarks()
		{
			
		}
		
		/** Adds a new Entry to the Table of Bookmarks including the Page number when a new Bookmark is set */
		public void add(Bookmark b)
		{
			if(!bookmarks.contains(b))
			{
				b.getPage().bookmarkPage();
				bookmarks.add(b);
			}
			
			sortBookmarksByPageNumber();
		}
		
		/** Removes an Entry to the Table of Bookmarks when an existing Bookmark is unset 
		 *  Returns TRUE if successful, FALSE if the Bookmark hasn't been previously set 
		 */
		public boolean remove(Bookmark b)
		{
			Bookmark removedBookmark;
			
			if(bookmarks.contains(b))
			{
				int index = bookmarks.indexOf(b);
								
				removedBookmark = bookmarks.remove(index);
				removedBookmark.getPage().removeBookmark();
				
				return true;
			}
			
			return false;
		}
		
		/** Retrieves the Bookmark at the specified index */
		public Bookmark getBookmarkAt(int index)
		{
			Bookmark theBookmark;
			
			if((index < 0) || (index >= bookmarks.size()))
				return null;
			
			if(!((theBookmark = (Bookmark)bookmarks.get(index)) == null))
				return theBookmark;
			else
				return null;
		}
		
		/** Returns the number of Bookmarks currently set in this Table Of Bookmarks */
		public int size()
		{
			return bookmarks.size();
		}
		
		/** Sorts the Table of Contents so that they are always listed in order of increasing page number */
		private void sortBookmarksByPageNumber()
		{
			for(int i = 0; i < bookmarks.size() - 1; i++)
				for(int j = i; j < bookmarks.size(); j++)
				{
					if(((Bookmark)bookmarks.get(j)).getPageNum() < ((Bookmark)bookmarks.get(i)).getPageNum())
					{
						Bookmark temp = (Bookmark)bookmarks.get(i);
						bookmarks.set(i, (Bookmark)bookmarks.get(j));
						bookmarks.set(j, temp);
					}
				}
		}
}
